<?php

namespace App\Http\Controllers;

use App\Jobs\FileJob;
use App\Models\FileModel;
use App\Models\FolderModel;
use App\Services\ElasticSearchService;
use App\Services\FileService;
use http\Client\Response;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class FileController extends Controller
{
    static function UPLOAD_ROOT() {
        return public_path('upload/');
    }

    /**
     * 文件搜索
     * @param Request $i
     * @return JsonResponse
     */
    public function search(Request $i) : JsonResponse {
        $keywords   = $i->input('keywords', '');
        $host       = config('app.url');
        if ($keywords != '') {
            $files  = FileService::search($keywords);
        } else {
            $files  = FileModel::all();
        }
        foreach($files as &$file) {
            $file['path']   = $host .'/upload/'.$file['path'];
            $file['thumb']  = $host . '/upload/'.self::thumbName($file['path']);
        }
        return self::success($files);
    }

    public static function thumbName($path) {
        $dir = dirname($path);
        $dir = $dir == '.' ? '' : $dir.'/';
        return $dir.pathinfo($path, PATHINFO_FILENAME).'-200.'.pathinfo($path, PATHINFO_EXTENSION);
    }

    /**
     * 遍历文件
     * @param Request $i
     * @return JsonResponse
     */
    public function scanFile(Request $i) : JsonResponse{
        $level  = $i->input('level', 1);    // 文件深度层级
        $pid    = $i->input('pid', 0);
        $docType= $i->input('docType', 0);  // 0:全部 1：文件 2：目录

        // 获取目录
        if ($docType == 2) {
            $files = FolderModel::where('pid', $pid)->get();
            if ($level >= 2) {
                foreach($files as $f) {
                    $child = FolderModel::where('pid', $f->id)->get();
                    if($child) {
                        foreach($child as $c){
                            $c->children = null;
                        }
                    }
                    $f->children = $child;
                }
            }
        } else {

            $folder = FolderModel::find($pid);
            $path = $folder->path . $folder->name;
            $files = FileModel::where('virtual_path', 'like', "/{$path}%")->get();
            $host   = config('app.url');
            foreach($files as $key => $file) {
                $files[$key]['url']     = $host . '/upload/' . str_replace(DIRECTORY_SEPARATOR,'/',$file['path']);
                $files[$key]['name']    = basename($file['virtual_path']);
                $files[$key]['thumb']   = $host . '/upload/'.self::thumbName($file['path']);
            }
        }

        return self::success($files);
    }

    /**
     * 文件上传
     * @param Request $i
     */
    public function upload(Request $i) {
        $file   = $i->file('file');
        $num    = $i->input('chunk');
        $name   = $i->input('name');
        $file->storeAs('upload', $name.'-'.$num);
        // 加入识别队列
        return self::success();
    }

    /**
     * 文件合并
     * @param Request $i
     * @return JsonResponse
     */
    public function merge(Request $i) {
        $chunks = $i->input('chunks');
        $ext    = $i->input('ext');
        $name   = $i->input('name');
        $note   = $i->input('note', '');
        $title  = $i->input('title');
        $savePath=$i->input('uploadPath');

        // 合并文件
        $file   = public_path('upload/'.time());
        $fs     = fopen($file, 'w');
        for ($i=1; $i<=$chunks; $i++) {
            $temp = storage_path('app/upload/'.$name.'-'.$i);
            fwrite($fs, file_get_contents($temp));
            unlink($temp);
        }
        fclose($fs);

        // 根据hash重新命名
        $hash       = md5_file($file);
        $rootPath   = self::UPLOAD_ROOT();
        rename($file, $rootPath.$hash.$ext);

        $type       = 'A';
        $title      = $savePath.'/'.basename($title);
        FileJob::dispatch($type, $rootPath, $hash.$ext, $title, $note);
        return self::success();
    }

    public function update(Request $i) {
        $name = $i->input('name');  // 文件哈希值
        $note = $i->input('note');

        // 根据名字搜索数据库文件信息
        $file = FileModel::find_by_hash($name);
        if (!$file) {
            return self::fail('文件不存在');
        }
        $elastic = new ElasticSearchService();
        $elastic->update($file->id, ['content' => $note]);
        return self::success();
    }
}
